package com.cacche;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.cacche.thread.ThreadPool;
import com.cacche.thread.ThreadTask;
import com.cacche.thread.WorkTask;
import com.shwread.httpsdk.util.NetUtil;
import com.shwread.httpsdk.util.Util;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.util.ArrayList;

import logic.util.FileUtil;
import logic.util.SDcardUtil;
import logic.util.logutil.LogUtil;


/**
 * @Title: Cache.java
 * @Package com.cacche
 * @Description: TODO(添加描述)
 * @author 刘章
 * @date 2014年2月20日 下午8:21:11
 */
public class Cache
{
	private static Cache              instance;
	private static ThreadPool         threadPool;
	private static Context            context;
	protected static PhotoMemoryCache imageMemoryCache = PhotoMemoryCache.getInstance();
	
	private Cache() {
		threadPool = ThreadPool.getInstance();
	}
	
	/**
	 * @Title: getInstance
	 * @Description:初始化缓存
	 * @param @param mcontext
	 * @param @param muser_id
	 * @param @return 设定文件
	 * @return ContactCache 返回类型
	 * @throws
	 * @date 2013-6-18 上午9:23:17
	 */
	public static Cache getInstance(Context mcontext) {
		if (instance == null)
		{
			instance = new Cache();
			context = mcontext;
		}
		return instance;
	}
	
	/**
	 * @Title: getImage
	 * @Description: 获取图像
	 * @param @param key
	 * @param @param httpPath
	 * @param @param handler 设定文件
	 * @return void 返回类型
	 * @throws
	 * @date 2014年2月20日 下午8:36:39
	 */
	public void getImage(String key, String httpPath, Handler handler) {
		if (handler == null) return;
		Bitmap bitmap = imageMemoryCache.getBitmap(key);
		if (bitmap != null)
		{
			log("key:" + key + "------从缓存中获取图像----");
			DoImageView(handler, bitmap);
			return;
		}
		//从本地磁盘获取
		if (SDcardUtil.isSDCARDMounted())
		{
			bitmap = FileUtil.getBitmap(LocakPath(key));
		}
		if (bitmap != null)
		{
			log("key:" + key + "------从磁盘获取图像----");
			//存到缓存
			imageMemoryCache.putBitmap(key, bitmap);
			DoImageView(handler, bitmap);
			return;
		}
		//可能是被回收了
		if (threadPool != null && Util.isNotEmpty(httpPath) && !httpPath.equals("null"))
		{
			if (Util.isEmpty(key)) key = httpPath.substring(httpPath.lastIndexOf("/") + 1);
			threadPool.addTask(new DoImageThread(key, httpPath, handler));
		}
	}
	
	/**
	 * @Title: delImage
	 * @Description: 删除图像
	 * @param @param key 设定文件
	 * @return void 返回类型
	 * @throws
	 * @date 2014年2月21日 上午2:25:53
	 */
	public void delImage(String key) {
		if (Util.isNotEmpty(key))
		{
			//删除缓存
			imageMemoryCache.removeBitmap(key);
			if (SDcardUtil.isSDCARDMounted())
			{
				//删除本地
				FileUtil.delFile(LocakPath(key));
			}
		}
	}
	
	/**
	 * @Title: DoImageView
	 * @Description: 将图片显示到控件上
	 * @param @param bitmap
	 * @return void 返回类型
	 * @throws
	 * @date 2013-5-31 下午6:07:26 what : 0: failed 1: success
	 */
	private void DoImageView(Handler handler, Bitmap bitmap) {
		if (bitmap != null)
		{
			Message msg = handler.obtainMessage(1, bitmap);
			if (Looper.myLooper() == Looper.getMainLooper())
			{
				handler.handleMessage(msg);
			}
			else
			{
				handler.sendMessage(msg);
			}
		}
	}
	
	/**
	 * @Title: LocakPath
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param key
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @throws
	 * @date 2014年2月20日 下午8:57:45
	 */
	private String LocakPath(String key) {
		return SDcardUtil.getImagePath() + File.separator + key;
	}
	
	/**
	 * @ClassName: DoImageThread
	 * @Description: 下载图像线程
	 * @author 刘章
	 * @date 2013-7-3 上午11:41:04
	 */
	private class DoImageThread
	        extends
	        ThreadTask
	{
		private String  key;
		private String  httpPath;
		private Handler handler;
		
		public DoImageThread(String key, String httpPath, Handler handler) {
			super();
			this.key = key;
			this.httpPath = httpPath;
			this.handler = handler;
			this.setTaskId(key);
		}
		
		@Override
		public ThreadTask[] TaskCore() {
			ArrayList<WorkTask> list = new ArrayList<WorkTask>();
			try
			{
				if (NetUtil.isNetworkConnected(context))
				{
					byte[] bytes = DownPhoto(httpPath);
					if (bytes != null)
					{
						Cache.log("key:" + key + "------从网络获取图像----");
						Bitmap bitmap = FileUtil.ByteToBitmap(bytes);
						//存本地
						if (SDcardUtil.isSDCARDMounted())
						{
							FileUtil.writeSDFile(LocakPath(key), bytes);
						}
						//存缓存
						imageMemoryCache.putBitmap(key, bitmap);
						DoImageView(handler, bitmap);
					}
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			return list.toArray(new WorkTask[0]);
		}
		
		@Override
		protected boolean needExecuteImmediate() {
			return false;
		}
		
		@Override
		public void log(int index) {
			Cache.log("Thread:[" + index + "] TaskID:[" + getTaskId() + "] 用时：" + (getFinishTime() - getBeginExceuteTime()));
		}
		
	}
	
	/**
	 * @Title: DownPhoto
	 * @Description: 下载图像
	 * @param @param httpPath
	 * @param @return 设定文件
	 * @return byte[] 返回类型
	 * @throws
	 * @date 2014年2月20日 下午8:51:57
	 */
	private byte[] DownPhoto(String httpPath) {
		byte[] result = null;
		//httpGet连接对象  
		HttpGet httpRequest = null;
		//取得HttpClient 对象  
		HttpClient httpclient = null;
		try
		{
			httpRequest = new HttpGet(httpPath);
			httpclient = new DefaultHttpClient();
			
			//请求httpClient ，取得HttpRestponse  
			HttpResponse httpResponse = httpclient.execute(httpRequest);
			int code = httpResponse.getStatusLine().getStatusCode();
			if (code == HttpStatus.SC_OK)
			{
				//取得相关信息 取得HttpEntiy  
				result = EntityUtils.toByteArray(httpResponse.getEntity());
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (httpRequest != null)
			{
				httpRequest.abort();
				httpRequest = null;
			}
			if (httpclient != null)
			{
				httpclient.getConnectionManager().shutdown();
				httpclient = null;
			}
		}
		return result;
	}
	
	public static void log(String msg) {
		LogUtil.d("CACHE", msg);
	}
	
	/************************************************ 缓存清理 *********************************************************/
	
	/**
	 * @Title: clear
	 * @Description:清理数据
	 * @param 设定文件
	 * @return void 返回类型
	 * @throws
	 * @date 2013-6-4 下午3:47:55
	 */
	public static void clear() {
		log("--------清除数据---------");
		imageMemoryCache.clear();
		if (threadPool != null)
		{
			threadPool.destroy();
			threadPool = null;
		}
		context = null;
		instance = null;
	}
}
